package com.tianya.forum.controller;


import com.tianya.forum.common.AppResult;
import com.tianya.forum.common.ResultCode;
import com.tianya.forum.config.AppConfig;
import com.tianya.forum.exception.ApplicationException;
import com.tianya.forum.model.Article;
import com.tianya.forum.model.User;
import com.tianya.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @ApiOperation(value = "发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam(value = "版块id")@RequestParam(value = "boardId") @NonNull Long boardid,
                            @ApiParam(value = "标题")@RequestParam(value = "title")@NonNull String title,
                            @ApiParam(value = "正文")@RequestParam(value = "content")@NonNull String content){

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //判断是否禁言
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //构造帖子对象
        Article article = new Article();
        article.setBoardId(boardid);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        //调用业务层
        articleService.creat(article);
        return AppResult.success();
    }

    /**
     * 根据版块Id查询帖⼦列表
     * @param boardId 版块ID
     * @return  帖子列表
     */
    @ApiOperation(value = "根据版块Id显示帖⼦列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(
            @ApiParam(value = "帖子ID")@RequestParam(value = "boardId", required = false) Long boardId){
        // 定义返回的集对象
        List<Article> result = null;
        // 根据传的参数返回不同板块的帖⼦列表
        if(boardId == null){
            // 参数为空时表⽰⾸⻚帖⼦列表
            result = articleService.selectAll();
        }else{
            // 参数不为空时表⽰指定版本的帖⼦列表
            result = articleService.selectByBoardId(boardId);
        }
        //如果为null，返回一个空JSON
        if(result == null){
            result = new ArrayList<>();
        }
        //返回结果
        return AppResult.success(result);
    }

    /**
     * 显示帖子详情
     * @param id 帖子ID
     * @return 帖子详情
     */
    @ApiOperation(value = "根据帖子ID获取详情")
    @GetMapping("/details")
    public AppResult<Article>  getDetails(HttpServletRequest request,
                                          @ApiParam(value = "帖子ID") @RequestParam(value = "id") @NonNull Long id){
        //调用Service
        Article article = articleService.selectDetailById(id);

        //判断是否为作者
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(article.getUserId() == user.getId()){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    /**
     * 更新帖子
     * @param id 帖子ID
     * @param title 标题
     * @param content 正文
     * @return 成功
     */
    @ApiOperation(value = "更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam(value = "帖子ID")@RequestParam(value = "id") @NonNull Long id,
                            @ApiParam(value = "标题")@RequestParam(value = "title") @NonNull String title,
                            @ApiParam(value = "正文")@RequestParam(value = "content") @NonNull String content){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //判断是否禁言
        if(user.getState() == 1){
            // ⽇志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //获取帖子原始数据
        Article article = articleService.selectById(id);
        // 数据校验
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 帖⼦状态异常
        if (article.getState() != 0 || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_FORBIDDEN);
        }
        //判断是否是作者
        if(! user.getId().equals(article.getUserId())){
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调⽤业务层
        articleService.modify(id,title,content);
        return AppResult.success();
    }

    /**
     * 点赞帖子
     * @param id 帖子ID
     * @return 成功
     */
    @ApiOperation(value = "点赞接口")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam(value = "帖子ID")@RequestParam(value = "id")@NonNull Long id){
        //检验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    /**
     * 删除帖子接口
     * @param id 帖子ID
     * @return 成功
     */
    @ApiOperation(value = "删除帖子")
    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam(value = "帖子ID")@RequestParam(value = "id")@NonNull Long id){

        // 1. ⽤⼾是否禁⾔
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖⼦信息
        Article article = articleService.selectById(id);
        // 2. 帖⼦是否存在或已删除
        if(article == null || article.getDeleteState()==1 ){
            log.warn(ResultCode.FAILED_ARTICLE_FORBIDDEN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_FORBIDDEN));
        }
        // 3. ⽤⼾是否是作者
        if(!article.getUserId().equals(user.getId())){
            return AppResult.success(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 调⽤Service执⾏删除
        articleService.deleteById(id);
        return AppResult.success();
    }

    /**
     * 根据⽤⼾Id查询帖⼦列表
     *
     * @param userId ⽤⼾Id
     * @return 指定版块的帖⼦列表
     */
    @ApiOperation("根据用户Id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam(value = "用户ID")@RequestParam(value = "userId", required = false) Long userId){
        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            List<Article> articles = articleService.selectByUserId(user.getId());
            return AppResult.success(articles);
        }

        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);

    }

}
